package es

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"github.com/elastic/go-elasticsearch/v8/esapi"
)

// ik_smart ik_max_word
func CreateMapping() error {
	// 检查索引是否存在
	existsReq := esapi.IndicesExistsRequest{
		Index: []string{"products"},
	}
	existsRes, err := existsReq.Do(context.Background(), Client)
	if err != nil {
		return fmt.Errorf("failed to check index existence: %w", err)
	}
	defer existsRes.Body.Close()

	// 如果索引已存在，则删除索引
	if existsRes.StatusCode == 200 {
		deleteReq := esapi.IndicesDeleteRequest{
			Index: []string{"products"},
		}
		deleteRes, err := deleteReq.Do(context.Background(), Client)
		if err != nil {
			return fmt.Errorf("failed to delete index: %w", err)
		}
		defer deleteRes.Body.Close()

		if deleteRes.IsError() {
			return fmt.Errorf("error response while deleting index: %s", deleteRes.String())
		}
		fmt.Println("Existing index 'products' deleted successfully.")
	}

	// 定义映射
	mapping := map[string]interface{}{
		"settings": map[string]interface{}{
			"analysis": map[string]interface{}{
				"analyzer": map[string]interface{}{
					"ik_english_analyzer": map[string]interface{}{
						"type":      "custom",
						"tokenizer": "ik_max_word",
						"filter":    []string{"lowercase", "english_stop"},
					},
				},
				"filter": map[string]interface{}{
					"english_stop": map[string]interface{}{
						"type":      "stop",
						"stopwords": "_english_",
					},
				},
			},
		},
		"mappings": map[string]interface{}{
			"properties": map[string]interface{}{
				"title": map[string]interface{}{
					"type":     "text",
					"analyzer": "ik_english_analyzer", // 确保 title 字段使用 ik_english_analyzer
				},
				"productId": map[string]interface{}{
					"type": "keyword",
				},
				"productType": map[string]interface{}{
					"type": "integer",
				},
				"skuid": map[string]interface{}{
					"type": "keyword",
				},
				"spec": map[string]interface{}{
					"type": "text",
				},
				"supplierId": map[string]interface{}{
					"type": "long",
				},
				"supplier": map[string]interface{}{
					"type": "text",
				},
				"barcode": map[string]interface{}{
					"type": "keyword",
				},
				"createdAt": map[string]interface{}{
					"type": "date",
				},
				"updatedAt": map[string]interface{}{
					"type": "date",
				},
				"status": map[string]interface{}{
					"type": "integer",
				},
			},
		},
	}

	body, err := json.Marshal(mapping)
	if err != nil {
		return fmt.Errorf("failed to marshal mapping: %w", err)
	}

	req := esapi.IndicesCreateRequest{
		Index: "products",
		Body:  bytes.NewReader(body),
	}

	res, err := req.Do(context.Background(), Client)
	if err != nil {
		return fmt.Errorf("failed to create index: %w", err)
	}
	defer res.Body.Close()

	if res.IsError() {
		return fmt.Errorf("error response: %s", res.String())
	}

	return nil
}
